package com.yanqu.road.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class BaseHttpServlet extends HttpServlet {

    private Logger logger = LogManager.getLogger(this.getClass().getName());

    protected void sendMessage(HttpServletResponse response, String msg) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (msg.length() < 66666) {
                logger.info("response msg:{}", msg);
            }
            response.getWriter().write(msg);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.error("send response error:" + e);
        }
    }
    protected void sendMessageB64(HttpServletResponse response, String msg, boolean b64) {
        if (b64) {
            try {
                msg = Base64.encodeBase64String(msg.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        sendMessage(response, msg);
    }

    public JSONObject get37ResultObj(int result, String msg){
        JSONObject resultObj = new JSONObject();
        resultObj.put("result", result);
        resultObj.put("msg", msg);
        return resultObj;
    }

    public void send37Result(HttpServletResponse response, int result, String msg){
        JSONObject resultObj = get37ResultObj(result, msg);
        sendMessage(response, resultObj.toJSONString());
    }
}
